import {
  _Awaitable,
  NavigationGuardReturn,
  RouteLocationNormalized,
} from "vue-router";
import { RouterExtraOptions } from "./app-router-type.ts";

export default (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  routerExtraOptions: Required<RouterExtraOptions>,
): _Awaitable<NavigationGuardReturn> => {
  const showLoading =
    typeof routerExtraOptions.showLoading === "function"
      ? routerExtraOptions.showLoading()
      : routerExtraOptions.showLoading;

  if (showLoading) {
    routerExtraOptions.showLoadingFunction();
  }

  routerExtraOptions.afterShowLoading(to, from);

  const matchRoutes = to.matched.filter((item) => {
    return item.path === to.path;
  });

  if (matchRoutes.length === 0) {
    return true;
  }

  const matchRoute = matchRoutes[0];

  if (matchRoute.meta.allow === undefined) {
    return typeof routerExtraOptions.allowDefault === "function"
      ? routerExtraOptions.allowDefault(to, from)
      : routerExtraOptions.allowDefault;
  }

  return typeof matchRoute.meta.allow === "function"
    ? matchRoute.meta.allow(to, from)
    : matchRoute.meta.allow;
};
